// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import 'babel-polyfill'
import Vue from 'vue'
import Es6Promise from 'es6-promise'

Es6Promise.polyfill()

import App from './App'
import router from './router'
import Cube from 'cube-ui'
import {getConfig, getTokenInfo, getUserInfo} from './config';

import {get, post} from "./utils/request";
import store from './store';

Date.prototype.pattern = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
String.prototype.convertDateFromString = function (dateString) {
    if (dateString) {
        dateString = dateString.replace(/-/g, "/");
        let date = new Date(dateString);
        return date;
    }
}

Vue.use(Cube);

Vue.config.productionTip = false;
Vue.prototype.$get = get;
Vue.prototype.$post = post;


let userInfo = getUserInfo();
store.commit("updateUserInfo", {userInfo: userInfo});
router.beforeEach((to, from, next) => {
    if (to.path != "/login" && to.path != "/config") {
        userInfo = getUserInfo();
        console.log(to.path, userInfo)
        if (userInfo.isLogin) {
            next();
        } else {
            next({path: "/login"})
        }
    } else {
        if (to.path == "/login") {
            userInfo = getUserInfo();
            if (userInfo.isLogin) {
                next({path: from.path})
            } else {
                next()
            }
        } else {
            next();
        }
    }
    // next()
})

/* eslint-disable no-new */
let vue = new Vue({
    el: '#app',
    router,
    store,
    components: {App},
    template: '<App/>'
});
window.Vue = Vue;

let getRegistrationID = function () {
    window.JPush.getRegistrationID(onGetRegistrationID);
};

let onGetRegistrationID = function (data) {
    try {
        console.log("JPushPlugin:registrationID is " + data);

        if (data.length === 0) {
            window.setTimeout(getRegistrationID, 1000);
        } else {
            let tokenInfo = getTokenInfo();
            if (tokenInfo) {
                window.JPush.setAlias({
                        sequence: 1,
                        alias: tokenInfo.userInfo.ID
                    },
                    function (result) {
                        //consoel.info(result.alias);
                        console.info("setAlias:", result);
                    },
                    function (error) {
                        // alert(error.code);
                        console.log(error)
                    });
            }

        }
    } catch (exception) {
        console.log(exception);
    }
};

let onOpenNotification = function (event) {
    console.info("onOpenNotification", event);
    try {
        var alertContent;
        if (device.platform == "Android") {
            alertContent = event.alert;
        } else {
            alertContent = event.aps.alert;
        }
        // alert("open Notification:" + alertContent);
    } catch (exception) {
        console.log("JPushPlugin:onOpenNotification" + exception);
    }
};

let onReceiveNotification = function (event) {
    console.info("onReceiveNotification", event);
    try {
        let alertContent;
        if (device.platform == "Android") {
            alertContent = event.alert;
        } else {
            alertContent = event.aps.alert;
        }
        saveNotification(alertContent);
    } catch (exception) {
        console.log(exception)
    }
};

function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}

function saveNotification(content) {
    let day = new Date();
    let time = day.toLocaleDateString();
    let message = {message: content, time: time, is_read: false}
    let notices = getNotification();
    if (notices.length > 0) {
        notices.splice(0, 0, message);
    } else {
        notices = [];
        notices.splice(0, 0, message);
    }
    window.localStorage.setItem("notices", JSON.stringify(notices));
    store.commit("updateNew", {is_new_message: true})
    store.commit("updateMessage", {notices: notices})

}

let getNotification = function () {
    let notices = window.localStorage.getItem("notices");
    return notices ? JSON.parse(notices) : [];
}

let onReceiveMessage = function (event) {
    console.info("onReceiveMessage", event);
    try {
        var message;
        if (device.platform == "Android") {
            message = event.message;
        } else {
            message = event.content;
        }

    } catch (exception) {
        console.log("JPushPlugin:onReceiveMessage-->" + exception);
    }
};

let onBackKeyDown = function (evt) {
    if (Vue.$route.path != "/login") {
        window.history.back()
    } else {
        throw new Error('Exit');
    }
}

let initJPush = function () {
    try {
        document.addEventListener("jpush.openNotification", onOpenNotification, false);
        document.addEventListener("jpush.receiveNotification", onReceiveNotification, false);
        document.addEventListener("jpush.receiveMessage", onReceiveMessage, false);
        window.JPush.init();
        window.setTimeout(getRegistrationID, 1000);
        if (device.platform != "Android") {
            window.JPush.setDebugModeFromIos();
            window.JPush.setApplicationIconBadgeNumber(0);
        } else {
            window.JPush.setDebugMode(true);
            window.JPush.setStatisticsOpen(true);
        }
    } catch (exception) {
        console.log(exception);
    }
}

let app = {
    // Application Constructor
    initialize: function () {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
        // document.addEventListener("backbutton", onBackKeyDown, false);

    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function () {
        this.receivedEvent('deviceready');
        initJPush();
        try {
            if (StatusBar) {
                StatusBar.styleDefault();
            }
        } catch (e) {
            console.log(e);
        }

        let notices = getNotification();
        store.commit("updateMessage", {notices: notices});

        try {
            let uuid = "";
            if (process.env.NODE_ENV === 'development') {
                // dev
                uuid = "B59E7CFD-D9FD-492B-9F70-4CBA84E736AF"
            } else {
                // build
                uuid = device.uuid;
            }
            console.log(uuid)
            store.commit("update_uuid", {uuid: uuid});

        } catch (e) {
            console.log(e)
        }


    },

    // Update DOM on a Received Event
    receivedEvent: function (id) {

    }

};


app.initialize();

if (process.env.NODE_ENV === 'development') {
    // dev
    app.onDeviceReady()
} else {
    // build
}